package com.enzoism.springboot.dive;

import com.enzoism.springboot.dive.dao.RegionDao;
import com.enzoism.springboot.dive.model.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class RegionService {
    @Autowired
    private RegionDao regionDao;

    /**
     * 数据库查询
     */
    public List<Region> selectRegionList(Region region) {
        return regionDao.selectRegionList();
    }

    /**
     * 得到子节点列表(得到下级区域)
     */
    public List<Region> buildAreaTree(List<Region> regions) {
        List<Region> tree = new ArrayList<>();
        for (Iterator<Region> it = regions.iterator(); it.hasNext(); ) {
            Region region = it.next();
            if (region.getPid() == 0) {
                recursionFn(regions, region); //递归列表
                tree.add(region);
            }
        }
        return tree;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<Region> list, Region region) {
        // 得到子节点列表
        List<Region> childList = getChildList(list, region);
        region.setChildren(childList);
        for (Region child : childList) {
            if (hasChild(list, child)) {
                //判断是否有子节点
                Iterator it = childList.iterator();
                while (it.hasNext()) {
                    Region n = (Region) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<Region> getChildList(List list, Region region) {
        List<Region> tlist = new ArrayList();
        Iterator<Region> it = list.iterator();
        while (it.hasNext()) {
            Region region1 = it.next();
            if (region1.getPid().longValue() == region.getId().longValue()) {
                tlist.add(region1);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<Region> list, Region region) {
        return getChildList(list, region).size() > 0 ? true : false;
    }
}